package com.imcoke.abchat.common.utils;

import com.imcoke.abchat.common.AppProperties;
import com.imcoke.abchat.web.service.UserDetailsImpl;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Author ccoke
 * @Description
 * @Date: 21:23 2017-11-27
 */
@Component
public class JwtTokenUtil {
    @Autowired
    private AppProperties mAppProperties;
    /*
    * 生成JWT
    * */
    public String generateToken(Map<String,Object> claims,Long expiration){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate(expiration))
                .signWith(SignatureAlgorithm.HS256,mAppProperties.getSecret())
                .compact();
    }

    /**
     * 获得系统当前时间
     */
    private Date generateExpirationDate(Long expiration){
        return new Date(System.currentTimeMillis()+expiration*1000);
    }


    /*
    * 将token转换成claims
    * */
    public Claims getClaimsFromToken(String token){
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(mAppProperties.getSecret())
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            claims = null;
        }
        return claims;
    }

    /*
    * 获取token的创建时间
    * */
    public Date getCreatedDateFromToken(String token){
        Date created;
        try{
            final Claims claims = getClaimsFromToken(token);
            created = new Date((Long)claims.get(AppProperties.KEYTIME));
        }catch (Exception e){
            created = null;
        }
        return created;
    }

    /*
    * 判断token是否在修改密码前创建
    * */
    public Boolean isCreatedBeforeLastPasswordReset(Date created,Date lastPasswordReset){
        return (lastPasswordReset != null && created.before(lastPasswordReset));
    }

    /*
    * 验证token是否有效
    * */
    public Boolean validateToken(String token,UserDetails userDetails){
        UserDetailsImpl user = (UserDetailsImpl) userDetails;
        final Date created = getCreatedDateFromToken(token);
        return (!isCreatedBeforeLastPasswordReset(created,user.getModifytime()));
    }
}
